package com.ky.manage.utils;

import android.text.TextUtils;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.MessageDigest;

/**
 * Created by dell on 2018/7/31.
 */

public class Md5Util {

    /**
     * 获取文件md5
     *
     * @param filePath
     * @return
     */
    public static String getFileMD5(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return "";
        }
        return getFileMD5(new File(filePath));
    }

    /**
     * 获取单个文件的MD5值！
     *
     * @param file
     * @return
     */
    public static String getFileMD5(File file) {
        if (null == file || !file.exists() || !file.isFile()) {
            return "";
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte[] buffer = new byte[8192];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        BigInteger bigInt = new BigInteger(1, digest.digest());
        String md5 = bigInt.toString(16);
        if (md5.length() < 32) {
            String b = "";
            for (int i = 0; i < 32 - md5.length(); i++) {
                b += "0";
            }
            return b + md5;
        } else {
            return md5;
        }
    }
}
